﻿Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Globalization
Imports System.IO

<ValueConversion(GetType(Image), GetType(BitmapImage))>
Public Class BitmapConverter
    Implements IValueConverter

    <System.Runtime.InteropServices.DllImport("gdi32.dll")> _
    Public Shared Function DeleteObject(hObject As IntPtr) As Boolean
    End Function

#Region "IValueConverter Members"

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
        ' empty images are empty...
        If value Is Nothing Then
            Return Nothing
        End If

        Dim image As System.Drawing.Image = DirectCast(value, System.Drawing.Image)
        ' Winforms Image we want to get the WPF Image from...
        Dim bitmap As BitmapImage = New System.Windows.Media.Imaging.BitmapImage()
        bitmap.BeginInit()
        Dim memoryStream As New MemoryStream()
        ' Save to a memory stream...
        image.Save(memoryStream, ImageFormat.Png)
        ' Rewind the stream...
        memoryStream.Seek(0, System.IO.SeekOrigin.Begin)
        bitmap.StreamSource = memoryStream
        bitmap.EndInit()
        Return bitmap
    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return Nothing
    End Function

#End Region
End Class